/* 
 * Copyright 2014 ShangDao.Ltd  All rights reserved.
 * SiChuan ShangDao.Ltd PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 
 * @ActLogin.java  2014-9-9 上午10:44:52 - Carson
 * @author YanXu
 * @email:981385016@qq.com
 * @version 1.0
 */

package com.android.tiango.baba.act;

import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.text.InputType;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.scsd.tiango.R;
import com.android.support.httpclient.HttpCallBack;
import com.android.support.httpclient.HttpClientAsync;
import com.android.support.httpclient.HttpParams;
import com.android.tiango.baba.BaBaseActivity;
import com.android.tiango.baba.cookie.HttpUrl;
import com.android.tiango.baba.cookie.ShareCookie;
import com.android.tiango.baba.entity.LoginEntity;
import com.android.tiango.baba.entity.UserModel;
import com.android.tiango.baba.fragment.FrHome;
import com.android.tiango.baba.util.CommUtil;
import com.android.tiango.baba.util.Constants;
import com.android.tiango.baba.util.SocialUtils;
import com.android.tiango.baba.util.StringUtils;
import com.android.tiango.baba.util.ToastUtils;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.utils.OauthHelper;

/**
 * 登录
 * 
 * @author suip
 * 
 */
public class ActLogin extends BaBaseActivity implements OnClickListener {

	private ImageView mFork, mDelete;
	private EditText mPhone, mPassword;// login 的手机号码账号和密码
	private ImageView mIsOpenPassword;// 控制密码是否显示为***
	private TextView mForget;
	private Button mLogin, mRegister;
	private ImageView mQQ, mXinLang;
	private LinearLayout mEnterLL;
	private ImageView mPhone_icon, mLock_icon;// 手机和密码锁小图标
	private boolean mIscheck = false;
	private SocialUtils socialUtils;
	private String mLoginName;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.layout_login);
		initView();
	}

	private void initView() {
		// TODO Auto-generated method stub
		mFork = (ImageView) findViewById(R.id.iv_fork_delete);
		mForget = (TextView) findViewById(R.id.tv_forget);
		mPhone = (EditText) findViewById(R.id.ic_enter).findViewById(
				R.id.et_phone);
		mPassword = (EditText) findViewById(R.id.ic_enter).findViewById(
				R.id.et_password);
		mDelete = (ImageView) findViewById(R.id.ic_enter).findViewById(
				R.id.iv_phone_delete);
		mIsOpenPassword = (ImageView) findViewById(R.id.ic_enter).findViewById(
				R.id.iv_passwordclose);
		mEnterLL = (LinearLayout) findViewById(R.id.ic_enter).findViewById(
				R.id.ll_enter);
		mPhone_icon = (ImageView) findViewById(R.id.ic_enter).findViewById(
				R.id.iv_phone);
		mLock_icon = (ImageView) findViewById(R.id.ic_enter).findViewById(
				R.id.iv_lock);
		mLogin = (Button) findViewById(R.id.bt_login);
		mRegister = (Button) findViewById(R.id.bt_register);
		mQQ = (ImageView) findViewById(R.id.iv_qq);
		mXinLang = (ImageView) findViewById(R.id.iv_xinlang);

		mDelete.setVisibility(View.VISIBLE);
		mPhone_icon.setBackgroundResource(R.drawable.phone2);
		mLock_icon.setBackgroundResource(R.drawable.lock2);
		mEnterLL.setBackgroundResource(R.drawable.frame_enter2);

		mQQ.setOnClickListener(this);
		mXinLang.setOnClickListener(this);
		mRegister.setOnClickListener(this);
		mFork.setOnClickListener(this);
		mDelete.setOnClickListener(this);
		mIsOpenPassword.setOnClickListener(this);
		mForget.setOnClickListener(this);
		mLogin.setOnClickListener(this);
		socialUtils = new SocialUtils();
		
		
		String phoneNumber=ShareCookie.getUserAccount();
		mPhone.setText(phoneNumber);

	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	    /**使用SSO授权必须添加如下代码 */  
	    UMSsoHandler ssoHandler = socialUtils.mController_Login.getConfig().getSsoHandler(requestCode);
	    if(ssoHandler != null){
	       ssoHandler.authorizeCallBack(requestCode, resultCode, data);
	    }
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_qq:
			UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(ActLogin.this,
					Constants.QQ_APPID, Constants.QQ_APPKEY);
			qqSsoHandler.addToSocialSDK();
			if (!OauthHelper.isAuthenticated(ActLogin.this, SHARE_MEDIA.QQ)) {
				// 没有授权 ，进入第三方登陆
				socialUtils.setOtherLogin(ActLogin.this, SHARE_MEDIA.QQ);
			} else {
				Toast.makeText(ActLogin.this, "QQ已经授权.", Toast.LENGTH_SHORT)
						.show();
				showActivity(ActThreeLogin.class, "QQ");
			}
			break;
		case R.id.iv_xinlang:
			// 设置新浪SSO handler
		//	socialUtils.mController_Login.getConfig().setSsoHandler(new SinaSsoHandler());
			boolean b = OauthHelper.isAuthenticated(ActLogin.this,SHARE_MEDIA.SINA);
			if (!b) {
				socialUtils.setOtherLogin(ActLogin.this, SHARE_MEDIA.SINA);
			} else {
				Toast.makeText(ActLogin.this, "新浪平台已经授权.", Toast.LENGTH_SHORT).show();
				showActivity(ActThreeLogin.class, "xinlang");
			}

			break;
		case R.id.bt_register:
			showActivity(ActRegister.class, false);
			break;
		case R.id.iv_fork_delete:
			finish();
			break;
		case R.id.iv_phone_delete:
			mPhone.setText("");
			break;
		case R.id.iv_passwordclose:
			if (mIscheck == false) {
				mIsOpenPassword.setImageResource(R.drawable.password_open);
				mPassword
						.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
				setCursor(mPassword);
				mIscheck = true;
			} else {
				mIsOpenPassword.setImageResource(R.drawable.password_close);
				mPassword.setInputType(InputType.TYPE_CLASS_TEXT
						| InputType.TYPE_TEXT_VARIATION_PASSWORD);
				setCursor(mPassword);
				mIscheck = false;
			}
			break;
		case R.id.tv_forget:
			showActivity(ActFindPassword.class, false);
			break;
		case R.id.bt_login:
			if (CommUtil.isNetworkAvailable(this)) {
				mLoginName = mPhone.getText().toString().trim();
				String upass = mPassword.getText().toString().trim();
				if (StringUtils.isEmpty(mLoginName)
						|| StringUtils.isEmpty(upass)) {
					Toast.makeText(ActLogin.this, "请填写有效用户名，密码！",
							Toast.LENGTH_LONG).show();
				} else {
					doLogin(mLoginName, upass);
				}
			} else {
				ToastUtils.showMessage("无网络连接");
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 登陆
	 * 
	 * @param uname
	 * @param upass
	 */
	private void doLogin(String uname, String upass) {
		HttpClientAsync client = HttpClientAsync.getInstance();
		HttpParams params = new HttpParams();
		params.put("userName", uname);
		params.put("password", upass);
		client.post(HttpUrl.getUrl(HttpUrl.USERLOGIN), params,
				new HttpCallBack() {
					@Override
					public void onHttpSuccess(Object ob) {
						System.out.println("ob :" + ob);
						dismissWaitingDialog();
						LoginEntity entity = (LoginEntity) ob;
						UserModel uModel = entity.getData();
						ShareCookie.setLoginAuth(true);// 标识登陆
						ShareCookie.saveUserInfo(uModel);

						// 跳转进入主页
						showActivity(ActHome.class, true);

					}

					@Override
					public void onHttpStarted() {
						showWaitingDialog("正在登陆...");
					}

					@Override
					public void onHttpFailure(Exception arg0, String arg1) {
						dismissWaitingDialog();
						if (!StringUtils.isEmpty(arg1)) {
							Toast.makeText(ActLogin.this, arg1,
									Toast.LENGTH_LONG).show();
						} else {
							Toast.makeText(ActLogin.this, "抱歉,请重新尝试",
									Toast.LENGTH_LONG).show();
						}
					}
				}, LoginEntity.class);
	}

	/**
	 * 光标位置
	 * 
	 * @param editText
	 */
	public void setCursor(EditText editText) {

		CharSequence text = editText.getText();
		// Debug.asserts(text instanceof Spannable);
		if (text instanceof Spannable) {
			Spannable spanText = (Spannable) text;
			Selection.setSelection(spanText, text.length());
		}
	}

}
